<template>
  <div class="chat-container">
    <el-card class="chat-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-select
              v-model="currentChatTarget"
              placeholder="选择咨询师"
              :disabled="!connected"
              @change="handleTargetChange"
              class="target-select"
              size="small"
            >
              <el-option
                v-for="user in consultants"
                :key="user"
                :label="user"
                :value="user"
              />
            </el-select>
            
            <div v-if="queuePosition !== null" class="queue-info">
              <el-tag type="warning" size="small">
                <i class="el-icon-time"></i> 排队中: 第 {{ queuePosition + 1 }} 位
              </el-tag>
            </div>
          </div>
          
          <div class="header-right">
            <el-tag v-if="connected" type="success" size="small">
              <i class="el-icon-success"></i> 已连接
            </el-tag>
            <el-tag v-else type="danger" size="small">
              <i class="el-icon-error"></i> 未连接
            </el-tag>
            <span class="username">{{ userName }}</span>
          </div>
        </div>
      </template>

      <div class="chat-messages" ref="messagesContainer">
        <div v-if="isInQueue" class="queue-message">
          <el-alert 
            title="您正在排队等待咨询" 
            type="info" 
            :closable="false"
            center
            show-icon
          />
        </div>
        
        <div v-if="messages.length === 0" class="empty-message">
          <el-empty description="暂无聊天记录" :image-size="100" />
        </div>
        
        <div v-for="(message, index) in filteredMessages" :key="index" class="message-item">
          <div v-if="message.type === 'system'" class="system-message">
            <span class="system-text">{{ message.content }}</span>
          </div>
          <div v-else class="user-message" :class="{ 'self-message': message.isSelf }">
            <div class="message-meta">
              <span class="message-sender">{{ message.sender }}</span>
              <span class="message-time">{{ formatTime(message.timestamp) }}</span>
            </div>
            <div class="message-content">
              <div class="message-bubble">{{ message.content }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-area">
        <el-input
          v-model="inputMessage"
          placeholder="请输入消息..."
          :disabled="!connected || isInQueue"
          @keyup.enter="sendMessage"
          class="message-input"
          size="small"
        >
          <template #append>
            <el-button
              type="primary"
              :disabled="!connected || !inputMessage || isInQueue"
              @click="sendMessage"
              size="small"
              class="send-button"
            >
              <i class="el-icon-s-promotion"></i> 发送
            </el-button>
          </template>
        </el-input>
      </div>
    </el-card>

    <div class="connection-controls">
      <div v-if="!connected" class="login-panel">
        <el-input 
          v-model="userName" 
          placeholder="请输入用户名" 
          size="small"
          class="username-input"
        >
          <template #prefix>
            <i class="el-icon-user"></i>
          </template>
        </el-input>
        <el-button
          type="primary"
          class="connect-button"
          :disabled="!userName"
          @click="connect"
          size="small"
        >
          <i class="el-icon-connection"></i> 开始对话
        </el-button>
      </div>
      <div v-else>
        <el-button 
          type="danger" 
          @click="disconnect" 
          size="small"
          class="disconnect-button"
        >
          <i class="el-icon-switch-button"></i> 离开聊天室
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { WebSocketUtil } from '../utils/websocket';

export default {
  name: 'ChatRoom',
  setup() {
    // 状态管理
    const messages = ref([]);
    const inputMessage = ref('');
    const userName = ref('');
    const connected = ref(false);
    const messagesContainer = ref(null);
    const currentChatTarget = ref('');
    const consultants = ref(['咨询师1', '咨询师2', '咨询师3']);
    const queuePosition = ref(null);
    
    const isInQueue = computed(() => queuePosition.value !== null && queuePosition.value > 0);
    const filteredMessages = computed(() => {
      if (!currentChatTarget.value) return [];
      return messages.value.filter(msg => 
        msg.type === 'system' || 
        msg.sender === currentChatTarget.value || 
        (msg.isSelf && msg.receiver === currentChatTarget.value)
      );
    });
    
    // WebSocket连接
    const wsUrl = 'ws://localhost:9988/chat';
    const websocket = new WebSocketUtil(wsUrl);
    
    // 连接WebSocket
    const connect = () => {
      if (!userName.value.trim()) {
        ElMessage.warning('请输入用户名');
        return;
      }

      websocket.connect(userName.value);
      
      websocket.addOpenHandler(() => {
        connected.value = true;
        addSystemMessage(`欢迎 ${userName.value} 进入聊天室`);
      });

      websocket.addMessageHandler((rawMessage) => {
        if (rawMessage.startsWith('[HISTORY]')) {
          const history = JSON.parse(rawMessage.substring(9));
          messages.value = history;
          scrollToBottom();
          return;
        }
        
        if (rawMessage.startsWith('[QUEUE_POSITION]')) {
          queuePosition.value = parseInt(rawMessage.substring(16));
          return;
        }
        
        if (rawMessage.startsWith('[QUEUE_START]')) {
          queuePosition.value = 0;
          addSystemMessage('您可以开始咨询了');
          return;
        }
        
        if (rawMessage.startsWith('[CONSULTANTS]')) {
          consultants.value = JSON.parse(rawMessage.substring(13));
          return;
        }
        
        // 处理普通消息
        messages.value.push({
          sender: rawMessage.split(':')[0],
          content: rawMessage.split(':')[1]?.trim() || '',
          timestamp: Date.now(),
          isSelf: rawMessage.startsWith(`${userName.value}:`)
        });
        scrollToBottom();
      });

      websocket.addErrorHandler(() => {
        ElMessage.error('连接出错，请重试');
        disconnect();
      });

      websocket.addCloseHandler(() => {
        connected.value = false;
        addSystemMessage('连接已断开');
      });
    };
    
    // 断开连接
    const disconnect = () => {
      websocket.disconnect();
      connected.value = false;
      currentChatTarget.value = '';
      queuePosition.value = null;
    };
    
    // 发送消息
    const sendMessage = () => {
      if (!inputMessage.value.trim() || !currentChatTarget.value) return;
      
      const privateMessage = `[PRIVATE]${userName.value}|${currentChatTarget.value}|${inputMessage.value}`;
      websocket.sendMessage(privateMessage);
      
      messages.value.push({
        sender: userName.value,
        receiver: currentChatTarget.value,
        content: inputMessage.value,
        timestamp: Date.now(),
        isSelf: true
      });
      
      inputMessage.value = '';
      scrollToBottom();
    };
    
    // 切换聊天对象
    const handleTargetChange = (consultant) => {
      if (!consultant) return;
      
      currentChatTarget.value = consultant;
      const joinMessage = `[JOIN_QUEUE]${userName.value}|${consultant}`;
      websocket.sendMessage(joinMessage);
      
      // 清空当前消息
      messages.value = [];
      addSystemMessage(`正在连接 ${consultant}...`);
    };
    
    // 添加系统消息
    const addSystemMessage = (content) => {
      messages.value.push({
        type: 'system',
        content,
        timestamp: Date.now()
      });
      scrollToBottom();
    };
    
    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    };
    
    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    };
    
    onUnmounted(() => {
      disconnect();
    });
    
    return {
      messages,
      filteredMessages,
      inputMessage,
      userName,
      connected,
      messagesContainer,
      currentChatTarget,
      consultants,
      queuePosition,
      isInQueue,
      connect,
      disconnect,
      sendMessage,
      handleTargetChange,
      formatTime
    };
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 15px;
}

.chat-card {
  height: 80vh;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eaeaea;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.target-select {
  width: 150px;
}

.queue-info {
  margin-left: 10px;
}

.username {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  background-color: #f5f7fa;
  scroll-behavior: smooth;
}

.empty-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.queue-message {
  margin-bottom: 15px;
}

.message-item {
  margin-bottom: 16px;
}

.system-message {
  text-align: center;
  margin: 10px 0;
}

.system-text {
  display: inline-block;
  padding: 4px 12px;
  background-color: #e6f7ff;
  border-radius: 4px;
  color: #1890ff;
  font-size: 12px;
}

.user-message {
  display: flex;
  flex-direction: column;
  max-width: 75%;
}

.self-message {
  align-items: flex-end;
}

.message-meta {
  margin-bottom: 4px;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.message-sender {
  font-weight: bold;
  margin-right: 8px;
  color: #333;
}

.message-time {
  font-size: 11px;
}

.message-content {
  display: flex;
}

.message-bubble {
  padding: 10px 14px;
  border-radius: 18px;
  line-height: 1.5;
  word-break: break-word;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.user-message:not(.self-message) .message-bubble {
  background-color: white;
  border-top-left-radius: 4px;
}

.self-message .message-bubble {
  background-color: #1890ff;
  color: white;
  border-top-right-radius: 4px;
}

.chat-input-area {
  padding: 12px 16px;
  border-top: 1px solid #eaeaea;
  background-color: #f8f9fa;
}

.message-input {
  border-radius: 20px;
  overflow: hidden;
}

.send-button {
  border-radius: 0 20px 20px 0;
}

.connection-controls {
  margin-top: 15px;
  text-align: center;
}

.login-panel {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.username-input {
  width: 200px;
}

.connect-button, .disconnect-button {
  border-radius: 20px;
  padding: 8px 20px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>